import * as THREE from '../../build/three.module.js'
import Stats from '../../jsm/libs/stats.module.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color( 0x101010 );

const camera = new THREE.PerspectiveCamera(65, innerWidth / innerHeight, 1, 20);
camera.position.z = 2;

const gmt = new THREE.BufferGeometry();

const positions = []
const colors = []

const vertexs = 200 * 3;

for(let i = 0; i < vertexs; i += 1) {
  const x = Math.random() - .5;
  const y = Math.random() - .5;
  const z = Math.random() - .5;

  positions.push(x, y, z);

  colors.push(
    Math.random() * 255,
    Math.random() * 255,
    Math.random() * 255,
    Math.random() * 255,
  );
}

const positionAttribute = new THREE.Float32BufferAttribute(positions, 3);
const colorAttribute = new THREE.Uint8BufferAttribute(colors, 4);

colorAttribute.normalized = true; // 将rgba颜色转换为 0-1 的值

gmt.setAttribute('position', positionAttribute);
gmt.setAttribute('color', colorAttribute);

const mtl = new THREE.RawShaderMaterial({
  uniforms: {
    time: { value: 1.0 }
  },
  side: THREE.DoubleSide,
  transparent: true,
  vertexShader: document.getElementById('vertexShader').textContent,
  fragmentShader: document.getElementById('fragmentShader').textContent
});

const mesh = new THREE.Mesh(gmt, mtl);
scene.add(mesh);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const state = new Stats();
document.body.appendChild(state.dom);

renderer.setAnimationLoop(() => {

  const time = performance.now();

  const obj = scene.children[0];
  obj.rotation.y = time * 0.0005;
  obj.material.uniforms.time.value = time * 0.005;

  renderer.render(scene, camera);
  state.update();

})

const handleWindowResize = () => {
  camera.aspect(innerWidth, innerHeight);
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);